/**
 * Created by Van <winddd1999@gmail.com> on 2016/10/7.
 */
/**
 * 添加图片
 * @param url
 */
function img_del_add(url) {
    if (img_del_config_init != true) {
        console.error('img_del not initial');
        return;
    }
    if (image_index == null) {
        image_index = 0;
    }
    if ($(img_del_parent_node) == null) {
        console.error('找不到元素');
        return;
    }
    var image_id = ++image_index;
    var image_box = $('<img />').attr('id', image_id);
    $(image_box).attr('src', url);
    $(img_del_parent_node).append(image_box);
    img_del_bind(image_id);
}
/**
 * 初始化配置
 * @param config
 */
function img_del_init(config) {
    if (config != null) {
        img_del_parent_node = config.parent;
        img_del_index = config.index == null ? 0 : config.index;
        img_del_config_init = true;
    }
}
/**
 * 绑定删除函数
 * @param func
 */
function img_del_listener_bind(func) {
    if (func == null) {
        console.error('没有设置默认删除函数');
        return;
    }
    if (typeof func == 'function') {
        img_del_deleted_function = func;
    } else {
        console.error(func + '不是一个function');
    }
}
img_del_bind_list = [];
function img_del_reload(del_id) {
    nodes = $('.img-del');
    parent = $(nodes).get(0).offsetParent;
    $(nodes).each(function (index, element) {
        parent.removeChild(element);
    });
    $(img_del_bind_list).each(function (index, element) {
        if (element != del_id) {
            img_del_bind(element);
        }
    });
}
function img_del_bind(id) {
    var img = document.getElementById(id);
    if (img != null) {
        img_del_bind_list.push(id);
        var parent = img.offsetParent;
        if (parent != null) {
            var node = $('<img>');
            node = node[0];
            node.style.position = 'absolute';
            var image_data = '';
            node.src = image_data;
            node.className = 'img-del';
            node.for_id = id;
            parent.appendChild(node);
            node.style.left = img.offsetLeft + img.offsetWidth - 16 + 'px';
            node.style.top = img.offsetTop + 'px';
            node.onclick = img_del_deleted;
        }
    }
}
function img_del_deleted() {
    var data_id = event.target.id;
    var _target = document.getElementById(event.target.for_id);
    var _parent = _target.parentNode;
    _parent.removeChild(_target);
    event.target.parentNode.removeChild(event.target);
    img_del_deleted_function(data_id, event.target);
    img_del_reload(data_id);
}
